﻿using ASmile.DBModel;
using ASmile.Extend;
using ASmile.ORM.Cores;

namespace ASmile.Com.Da
{
    public class DictComTypeBLL : BLLCrudBase<ArgPageData, Dict_CommonType>,  IDictComTypeBLL
    {
        protected override void SetQuery(QueryCondition<Dict_CommonType> query, ArgPageData arg)
        {
            query.WhereAnd(s => s.IsUse == true);

            if (arg.SearchVal.IsNotEmpty())
            {
                string likeStr = $"%{arg.SearchVal}%";
                query.WhereAnd(s =>
                    s.WEx_Like(s.TypeName, likeStr) ||
                    s.WEx_Like(s.TypeCaption, likeStr) ||
                    s.WEx_Like(s.TypeCaptionCode, likeStr) ||
                    s.WEx_Like(s.TypeNo, likeStr)
                    );
            }
        }

        protected override ApiResult<string> VerifyModel(Dict_CommonType model, bool isAdd)
        {
            if (model.TypeNo == 0)
            {
                return RetErr(nameof(model.TypeNo), "类型编码不能为空");
            }
            if (model.TypeName.IsEmpty())
            {
                return RetErr(nameof(model.TypeName), "类型名称不能为空");
            }
            if (model.TypeCaption.IsEmpty())
            {
                return RetErr(nameof(model.TypeCaption), "类型标题不能为空");
            }
            if (isAdd)
            {
                if (DB.QueryExist<Dict_CommonType>(s => s.TypeNo == model.TypeNo))
                {
                    return RetErr(nameof(model.TypeNo), "类型编码已经存在");
                }
            }
            if (DB.QueryExist<Dict_CommonType>(s => s.TypeName == model.TypeName && s.TypeNo != model.TypeNo))
            {
                return RetErr(nameof(model.TypeNo), "类型名称已经存在");
            }

            if (isAdd)
            {
                return RetOK(model.TypeNo.ToString(), "新增成功");
            }
            else
            {
                model.ClearChangedState("TypeNo");
                return RetOK("", "保存成功");
            }
        }

        /// <summary>
        /// 更新排序值
        /// </summary>
        public ApiResult SetOrderNo(ArgSetSortNo arg)
        {
            Dict_CommonType m = new Dict_CommonType
            { 
                TypeNo = arg.Id.ToShort(),
                SortNo = arg.SortNo
            };

            var ret = DB.Update(m);
            if (ret.RowCount == 1)
            {
                return RetOK($"设置排序成功");
            }
            return RetErr("设置排序失败");
        }
    }
}